package com.wxg.config.alimq;

import com.aliyun.openservices.ons.api.*;
import com.wxg.domain.MqConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Properties;

/**
 * @author void
 * @date 2020/9/29 14:26
 * @desc
 */
@Slf4j
@Configuration
@Conditional(value = AliRocketCondition.class)
public class AliRocketProducer {

    @Autowired
    private AliRocketMqProperties aliRocketMqProperties;
    
    @Bean
    public Producer getMyProducer(){
        return getProducer(MqConstant.Group.GID_VOID_1);
    }

    /**
     * 通用获取生产者
     * @param group
     * @return
     */
    private Producer getProducer(MqConstant.Group group) {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.AccessKey, aliRocketMqProperties.getAccessKeyId());
        properties.put(PropertyKeyConst.SecretKey, aliRocketMqProperties.getAccessKeySecret());
        //设置发送超时时间，单位毫秒。
        properties.setProperty(PropertyKeyConst.SendMsgTimeoutMillis, "3000");
        // 设置 TCP 接入域名，进入控制台的实例详情页面的 TCP 协议客户端接入点区域查看。
        properties.put(PropertyKeyConst.NAMESRV_ADDR, "XXX");
        Producer producer = ONSFactory.createProducer(properties);
        // 在发送消息前，必须调用 start 方法来启动 Producer，只需调用一次即可。
        producer.start();

        //循环发送消息。
        for (int i = 0; i < 100; i++){
            Message msg = new Message( "TopicTestMQ", "TagA", "你好rocketmq 阿里云版本".getBytes());
            try {
                SendResult sendResult = producer.send(msg);
                // 同步发送消息，只要不抛异常就是成功。
                if (sendResult != null) {
                    System.out.println(new Date() + " Send mq message success. Topic is:" + msg.getTopic() + " msgId is: " + sendResult.getMessageId());
                }
            } catch (Exception e) {
                // 消息发送失败，需要进行重试处理，可重新发送这条消息或持久化这条数据进行补偿处理。
                System.out.println(new Date() + " Send mq message failed. Topic is:" + msg.getTopic());
                e.printStackTrace();
            }
        }
        return producer;
    }
}
